using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Core.Common;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Mars.Got;

namespace Yoozoo.Gameplay.Liberty.PlayerController
{
    public class MoveBehavior : BehaviorBase
    {
        [SerializeField]
        private float turnSmoothing = 0.06f;
        
        // 瞄准时的平滑速度
        [SerializeField]
        private float aimTurnSmoothing = 0.2f;

        [SerializeField]
        private float aimMoveBackThreshold = -0.2f;

        // 当前速度的符号，用于后退
        [SerializeField]
        private int runSpeedFlag = 1;
        
        [SerializeField]
        private float curSpeed;

        [SerializeField] 
        private Vector3 targetDirection;
        
        private float _isColliding;

        public float rotationSpeed = 5;

        public float smoothFactor = 5;
        // 瞄准修复方向
        private Vector3 repairAimDirection = Vector3.forward;
        // 是否需要修复方向
        private bool needRepairAimDirection = false;
        
        
        public override void OnUpdate()
        {
            
        }


        public override void OnFixedUpdate()
        {
            // 重置下数据，防止被提前return导致数据不正确
            AIData aiData = behaviourManager.aiEntity.data;
            aiData.moveDirection = Vector3.zero;
            
            if (behaviourManager.rigidBody == null)
            {
                return;
            }

            if (aiData.hp <=0)
            {
                return;
            }
            float horizontal = behaviourManager.playInput.HorRealValue;
            float vertical = behaviourManager.playInput.VerRealValue;

            Rotating(horizontal, vertical);
            Moving(horizontal,vertical);
        }

        private void Rotating(float horizontal, float vertical)
        {
            // 当前状态是否不可移动
            if (behaviourManager.aiEntity.data.cannotAnimationStateMove)
            {
                return;
            }
            
            // 获取相机在XZ平面的方向
            Vector3 cameraForward = behaviourManager.playerCamera.transform.TransformDirection(Vector3.forward);
            cameraForward.y = 0.0f;
            cameraForward = cameraForward.normalized;

            // Calculate target direction based on camera forward and direction key.
            // 根据 相机朝向 和 玩家输入方向 计算出 玩家目标方向
            Vector3 cameraRight = new Vector3(cameraForward.z, 0, -cameraForward.x);
            targetDirection = cameraForward * vertical + cameraRight * horizontal;
            
            // 玩家当前方向
            Vector3 currentForward = behaviourManager.aiEntity.data.forward;
            currentForward.y = 0;

            runSpeedFlag = 1;
            // 如果当前作战状态支持瞄准
            if (behaviourManager.aiEntity.data.aimingState != AimingState.None)
            {
                // // IK角度限制
                // float IKLimitMin = -10;
                // float IKLimitMax = 15;
                // var QualityHandGunAimIKLimits = behaviourManager.aiEntity.viewer.animationAgent.IKAgent.QualityHandGunAimIKLimits;
                // KeyValuePair<int, int> IKLimitPair;
                // if (QualityHandGunAimIKLimits.TryGetValue(QualityManager.Inst.CurrentQuality, out IKLimitPair))
                // {
                //     IKLimitMin = IKLimitPair.Key;
                //     IKLimitMax = IKLimitPair.Value;
                // }

                bool needRotate = false;
                // 确认目标方向
                if (behaviourManager.IsMoving() && targetDirection != Vector3.zero)
                {
                    // 移动
                    needRotate = true;
                    needRepairAimDirection = false;

                    targetDirection = cameraForward;
                    // // 有目标，自动瞄准，不允许玩家背对目标
                    // if (behaviourManager.aiEntity.battleAgent.currentLockTarget)
                    // {
                    //     Vector3 lockTargetDirection = behaviourManager.aiEntity.battleAgent.currentLockTarget.viewer.animator.transform.position - behaviourManager.rigidBody.transform.position;
                    //     float lockTargetDirectionDotTargetDirection = Vector3.Dot(lockTargetDirection.normalized, targetDirection);
                    //     if (lockTargetDirectionDotTargetDirection < 0)
                    //     {
                    //         // 背对敌人，重新锁定新的目标
                    //         LibertyAIUtils.PlayerController.playerLockTargetHelper.RefreshCurrentLockTarget();
                    //     }
                    // }
                    //
                    // // 不允许玩家角色面朝相机
                    // {
                    //     float cameraForwardDotTargetDirection = Vector3.Dot(cameraForward, targetDirection);
                    //     if (cameraForwardDotTargetDirection < aimMoveBackThreshold)
                    //     {
                    //         // 面朝相机
                    //         targetDirection = -targetDirection;
                    //         runSpeedFlag = -1;
                    //     }
                    // }
                }
                // else if (behaviourManager.aiEntity.battleAgent.currentLockTarget)
                // {
                //     // 待机状态，有目标，自动瞄准 （目标方向：由玩家指向目标的方向）
                //     
                //     // 转向目标方向
                //     targetDirection = behaviourManager.aiEntity.battleAgent.currentLockTarget.viewer.animator.transform.position - behaviourManager.rigidBody.transform.position;
                //     targetDirection.y = 0;
                //     targetDirection = targetDirection.normalized;
                //     
                //     // 检测是否超过IK旋转限制
                //     float signedDegree = Vector3.SignedAngle(currentForward, targetDirection, Vector3.up);
                //     if (signedDegree<=IKLimitMin || IKLimitMax<=signedDegree)
                //     {
                //         needRepairAimDirection = true;
                //         repairAimDirection = targetDirection;
                //     }
                //
                //     // 如果当前正在修正方向
                //     if (needRepairAimDirection)
                //     {
                //         needRotate = true;
                //         targetDirection = repairAimDirection;
                //     }
                // }
                else if(LibertyAIUtils.PlayerController.playerLockTargetHelper.UseFreeAim)
                {
                    // 待机状态，无目标，自由瞄准 （目标方向：相机forward）
                    targetDirection = cameraForward;

                    // 检测是否超过旋转限制
                    // float signedDegree = Vector3.SignedAngle(currentForward, targetDirection, Vector3.up);
                    // UnityEngine.Debug.LogError($"signedDegree: {signedDegree}");
                    // if (signedDegree<=IKLimitMin || IKLimitMax<=signedDegree)
                    {
                        needRepairAimDirection = true;
                        repairAimDirection = targetDirection;
                    }
                    
                    // 如果当前正在修正方向
                    if (needRepairAimDirection)
                    {
                        needRotate = true;
                        targetDirection = repairAimDirection;
                    }
                }

                if (needRotate)
                {
                    // 判断是否顺时针旋转
                    Vector3 currentRight = new Vector3(currentForward.z, 0, -currentForward.x);
                    // 是否顺时针旋转，持枪旋转一定要经过角色Forward，并不一定要沿最短路径 (targetDirection在currentForward的右边，或 cameraForward在currentForward和targetDiretion之间)
                    bool clockwise = Vector3.Dot(currentRight, targetDirection) >= 0 || (Vector3.Dot(cameraRight, currentForward)<0 && Vector3.Dot(cameraRight, targetDirection)>0);
                    // if ((behaviourManager.IsMoving() && targetDirection != Vector3.zero))
                    // {
                    //     UnityEngine.Debug.LogError($"clockwise: {clockwise}, 右边: {Vector3.Dot(currentRight, targetDirection) >= 0}, 之间: {(Vector3.Dot(cameraRight, currentForward)<=0 && Vector3.Dot(cameraRight, targetDirection)>=0)}");
                    // }

                    Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
                    float targetEulerY = targetRotation.eulerAngles.y;
                    float currentEulerY = behaviourManager.aiEntity.data.CurrentLerpRotation.y;
                    
                    if (clockwise)
                    {
                        // 顺时针
                        if (targetEulerY < currentEulerY)
                        {
                            targetEulerY += 365;
                        }
                    }
                    else
                    {
                        // 逆时针
                        if (targetEulerY > currentEulerY)
                        {
                            targetEulerY -= 365;
                        }
                    }

                    // Vector3 newEulerAngles = new Vector3(0, Mathf.SmoothStep(currentEulerY, targetEulerY, aimTurnSmoothing), 0);
                    behaviourManager.aiEntity.data.aimDirection = targetDirection;
                    Vector3 newEulerAngles = new Vector3(0, targetEulerY, 0);
                    behaviourManager.aiEntity.AssignFixedRotation(newEulerAngles);
                    behaviourManager.LastDirection = newEulerAngles;
                    // UnityEngine.Debug.LogError($"newEulerAnglesY: {newEulerAngles.y}, currentEulerAnglesY: {currentEulerY}, targetEulerAnglesY: {targetEulerY}");

                    // 如果当前正在修正方向，检测方向是否修正完成
                    if (needRepairAimDirection)
                    {
                        currentForward = behaviourManager.aiEntity.data.forward;
                        currentForward.y = 0;
                        
                        // 允许的误差绝对值
                        float repairOffset = 5;
                        // 计算误差
                        float signedDegree = Vector3.SignedAngle(currentForward, targetDirection, Vector3.up);
                        if (-repairOffset<signedDegree && signedDegree<repairOffset)
                        {
                            // 修正完成
                            needRepairAimDirection = false;
                        }
                    }
                    
                }
            }
            else if((behaviourManager.IsMoving() && targetDirection != Vector3.zero))
            {
                needRepairAimDirection = false;
                Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
                // 这里使用Slerp进行平滑旋转
                Quaternion newRotation = Quaternion.Slerp(behaviourManager.aiEntity.data.rotation, targetRotation, rotationSpeed * Time.fixedDeltaTime);
                behaviourManager.aiEntity.SetRotation(newRotation.eulerAngles);
                behaviourManager.LastDirection = targetDirection;
                
                // 平滑过渡到目标方向
                //UnityEngine.Debug.Log("horizontal:"+ horizontal + ", vertical:"+ vertical);
                // Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
                // behaviourManager.aiEntity.AssignFixedRotation(targetRotation.eulerAngles);
//                behaviourManager.rigidBody.MoveRotation(newRotation);
                // behaviourManager.LastDirection = targetDirection;
                //UnityEngine.Debug.Log("平滑 newRotation:" + newRotation);
                //UnityEngine.Debug.Log("平滑 targetDirection:" + targetDirection);
                //UnityEngine.Debug.Log("角色 localEulerAngles:" + behaviourManager.rigidBody.transform.localEulerAngles);
            }
            // 静止状态，忽略相机方向，重定位角色方向。
            else if(!(Mathf.Abs(horizontal) > 0.9 || Mathf.Abs(vertical) > 0.9))
            {
                needRepairAimDirection = false;
                
                behaviourManager.Repositioning(turnSmoothing);
            }

        }


        private void Moving(float horizontal, float vertical)
        {
            AIEntity aiEntity = behaviourManager.aiEntity;
            AIData aiData = aiEntity.data;
            
            // 当前状态是否不可移动
            if (behaviourManager.aiEntity.data.cannotAnimationStateMove)
            {
                aiData.moveSpeed = 0;
                return;
            }
            if (!behaviourManager.CanMove)
            {
                aiData.moveSpeed = 0;
                return;
            }

            Vector3 joystickDirection = new Vector3(horizontal, 0, vertical);
            // 根据摇杆偏移量，计算移动速度
            //Debug.LogError($"Mathf.MoveTowards({aiData.moveSpeed}, {5 * joystickDirection.magnitude}, {AIData.moveAccelerrate*Time.fixedDeltaTime})={Mathf.MoveTowards(aiData.moveSpeed, 5 * joystickDirection.magnitude, AIData.moveAccelerrate*Time.fixedDeltaTime)}");
            aiData.moveSpeed = Mathf.MoveTowards(aiData.moveSpeed,  aiEntity.propertyDataConfig.move_speed * joystickDirection.magnitude * aiData.moveSpeedFactor, AIData.moveAccelerrate*Time.fixedDeltaTime);
            // 根据相机和摇杆方向，计算移动方向
            Quaternion cameraRotation = behaviourManager.playerCamera.transform.rotation;
            aiData.moveDirection = (cameraRotation*joystickDirection).normalized;
            
            Vector2 dir = new Vector2(horizontal, vertical);
            float targetMagnitude = Vector2.ClampMagnitude(dir, 1f).magnitude;
            curSpeed = Mathf.Lerp(curSpeed, targetMagnitude, smoothFactor * Time.fixedDeltaTime); // 使用Lerp平滑过渡到新的速度

            behaviourManager.animInput.SetSpeed(curSpeed*aiData.moveSpeedFactor);
        }
        
    }
}